<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\controller;
use app\BaseController;
use think\facade\View;
use think\facade\Db;
use app\admin\model\UserModel;
use think\facade\Session;
use think\facade\Cache;
class Login extends BaseController
{
    //用户登录
    public function index()
    {        
        if(request()->isPost()) {
            //数据验证
            $data=$this->request->only(['username','password','vercode'],'post',null);
            $validate = new \app\admin\validate\LoginValidate;            
            $result = $validate->check($data);
            if(!$result){
                $this->error($validate->getError());
            }
            //验证码校验
            if(!captcha_check($data['vercode'])){
                $this->error("验证码错误");
            };  
            //检测登录次数
            $this->checkLoginNum();            
            //查询用户是否存在
            $user = UserModel::where('username',$data["username"])->find();
            if(!$user){
                Db::name('user_login_log')->save(array(
                    "user_id"=>0,
                    "username"=>$data["username"],
                    "addtime"=>time(),
                    "status"=>0,
                    "ip"=>get_client_ip(),
                    "note"=>"用户名错误",
                ));                
                $this->error("用户名或者密码错误");
            }
            //检验密码
            if($user["password"]!=md6($data["password"],$user['salt'])){
                Db::name('user_login_log')->save(array(
                    "user_id"=>$user["user_id"],
                    "username"=>$user["username"],
                    "addtime"=>time(),
                    "status"=>0,
                    "ip"=>get_client_ip(),
                    "note"=>"密码错误",
                ));                  
                $this->error("用户名或者密码错误");
            }
            if(!$user["status"]){
                $this->error("当前用户已被禁用");
            }            
            //设置token,最后登录时间，并且每次登录salt都会重新生成，这样更安全
            $token=md6(make_random());
            UserModel::update(array(
                "user_id"=>$user["user_id"],
                "login_num"=>$user["login_num"]+1,
                "last_login_time"=>time(),
                "token"=>$token,
            ));               
            //设置登录
            Session::set('user_id',$user['user_id']);
            Session::set('username',$user['username']);
            Session::set('token',$token);
            //记录登录日志
            Db::name('user_login_log')->save(array(
                "user_id"=>$user["user_id"],
                "username"=>$user["username"],
                "addtime"=>time(),
                "status"=>1,
                "ip"=>get_client_ip(),
                "note"=>"登录成功",
            ));
            //清除登录次数
            $this->clearLoginNum();              
            //
            $this->success("登录成功",url("index/index"));
        }else{
            return View::fetch();
        }     
    }
    //登录次数判断
    final private function checkLoginNum(){
        $ipName=md5(get_client_ip());
        $errorLoginNum=Cache::get($ipName);
        if($errorLoginNum>=config("login.error_num")){
            return $this->error("登录次数已超出限制，请在".config("login.relogin_time")."分钟后再登录");
        }else{
            Cache::set($ipName,$errorLoginNum+1,config("login.relogin_time")*60);
        }
    }  
    //清除登录次数判断
    final private function clearLoginNum(){
        $ipName=md5(get_client_ip());
        Cache::delete($ipName);
    }     
    //取消登录
    public function loginOut(){
        //删除用户登录的session
        Session::delete('user_id');
        Session::delete('username');
        Session::delete('token');
        //跳转登录页
        $this->success("退出成功",url("index"));
    }
    //验证码
    public function captcha(){
        return \think\captcha\facade\Captcha::create();    
    }    
}
